package com.shortlink.server.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shortlink.server.dao.entity.ShortLinkStatsRecordDO;
import com.shortlink.server.dao.entity.ShortLinkTodayBaseStatsDO;
import com.shortlink.server.dao.mapper.ShortLinkStatsRecordMapper;
import com.shortlink.server.dto.shortlinkmapper.ShortLinkReqDTO;
import com.shortlink.server.dto.shortlinkstats.ShortLinkTodayBaseStatsRespDTO;
import com.shortlink.server.service.ShortLinkStatsRecordService;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 监控记录服务接口实现层
 *
 * @author wp
 */
@Service
public class ShortLinkStatsRecordServiceImpl extends ServiceImpl<ShortLinkStatsRecordMapper, ShortLinkStatsRecordDO> implements ShortLinkStatsRecordService {
    @Override
    public List<ShortLinkTodayBaseStatsRespDTO> batchGetShortLinkTodayBaseStats(List<ShortLinkReqDTO> shortLinks) {
        List<ShortLinkTodayBaseStatsDO> shortLinkTodayBaseStatsList = baseMapper.batchGetShortLinkBaseStats(shortLinks, LocalDate.now());
        Map<ShortLinkReqDTO, ShortLinkTodayBaseStatsDO> todayBaseStatsMap = shortLinkTodayBaseStatsList.stream()
                .collect(Collectors.toMap(shortLinkTodayBaseStatsDO -> new ShortLinkReqDTO(shortLinkTodayBaseStatsDO.getDomain(), shortLinkTodayBaseStatsDO.getShortUri()),
                        shortLinkTodayBaseStatsDO -> shortLinkTodayBaseStatsDO));
        return shortLinks.stream()
                .map(shortLink -> {
                    ShortLinkTodayBaseStatsRespDTO respDTO = new ShortLinkTodayBaseStatsRespDTO();
                    ShortLinkTodayBaseStatsDO todayDO = todayBaseStatsMap.get(shortLink);
                    if (todayDO == null) {
                        return respDTO;
                    }
                    respDTO.setNewUv(todayDO.getNewUv());
                    respDTO.setNewPv(todayDO.getPv());
                    respDTO.setNewIp(todayDO.getNewIp());
                    respDTO.setUv(todayDO.getUv());
                    respDTO.setPv(todayDO.getPv());
                    respDTO.setIp(todayDO.getIp());
                    return respDTO;
                })
                .toList();
    }
}
